<template>
  <div>
    <!-- 查询窗口 -->
    <el-form ref="queryForm" :model="queryParams" class="form">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-form-item size="small" prop="productSn" label-width="80px">
            <label slot="label" >{{$t('product_item_product_44')}}</label>
            <el-input
              v-model="queryParams.productSn"
              clearable
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item size="small" prop="productName" label-width="80px">
            <label slot="label">{{$t('product_item_product_45')}}</label>
            <el-input
              v-model="queryParams.productName"
              clearable
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item size="small" prop="minSalePrice" label-width="80px">
            <label slot="label">{{$t('product_item_product_46')}}</label>
            <el-input
              v-model="queryParams.minSalePrice"
              clearable
              style="width: 100px"
            />
            —————
            <el-input
              v-model="queryParams.maxSalePrice"
              clearable
              style="width: 100px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-form-item
            :label="$t('product_item_product_47')"
            size="small"
            prop="isParent"
            label-width="80px"
          >
            <div class="block">
              <el-cascader
                v-model="queryParams.categoryList"
                :options="categoryTree"
                :props="{
                  expandTrigger: 'hover',
                  multiple: true,
                  checkStrictly: true,
                }"
                clearable
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item
            :label="$t('product_item_product_48')"
            size="small"
            prop="status"
            label-width="80px"
          >
            <el-select v-model="queryParams.status" :placeholder="$t('product_item_product_49')">
              <el-option
                v-for="item in StatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            :label="$t('product_item_product_50')"
            size="small"
            prop="createTime"
            label-width="80px"
          >
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-:separator="$t('product_item_product_51')"
              start-:placeholder="$t('product_item_product_52')"
              end-:placeholder="$t('product_item_product_53')"
              style="width: 280px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item size="small">
            <el-button
              v-hasAuthority="['product:item:list']"
              type="primary"
              class="query"
              @click="handleQuery"
            >{{$t('product_item_product_54')}}</el-button>
            <el-button
              v-hasAuthority="['product:item:list']"
              type="primary"
              style="width: 60px; margin-left: 40px"
              @click="resetQuery"
            >{{$t('product_item_product_55')}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <el-row class="button-row">
      <el-button
        v-hasRole="['admin', 'purchaser']"
        mode="hide"
        type="warning"
        :disabled="!isMultipleSelected"
        class="warning"
        @click="batchOffProduct"
      >{{$t('product_item_product_56')}}</el-button>
      <el-button
        v-hasRole="['admin', 'purchaser']"
        mode="hide"
        type="danger"
        :disabled="!isMultipleSelected"
        class="deletes"
        @click="handleProductDelete"
      >{{$t('product_item_product_57')}}</el-button>
      <el-button
        v-hasRole="['admin', 'purchaser']"
        mode="hide"
        class="insertButton"
        @click="handleAddProduct"
      >{{$t('product_item_product_58')}}</el-button>
      <el-button
        v-hasRole="['admin', 'purchaser']"
        type="success"
        mode="hide"
        @click="handleExportAll"
      >{{$t('product_item_product_59')}}</el-button>
      <el-upload
        class="upload-demo"
        :http-request="httpRequest"
        :on-preview="handlePreview"
        action="http://localhost"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="excelList"
        :before-upload="handleBeforeUpload"
        :show-file-list="false"
        style="display: inline-block"
      >
        <el-button
          v-hasRole="['admin', 'purchaser']"
          size="small"
          type="success"
          class="insertButton"
        >{{$t('product_item_product_60')}}</el-button>
        <div  v-hasRole="['admin', 'purchaser']" slot="tip" class="el-upload__tip">{{$t('product_item_product_61')}}</div>
      </el-upload>
    </el-row>
    <!-- 数据展示Table -->
    <el-table
      ref="DataTable"
      v-loading="loading"
      border
      :data="dataList"
      style="border: 1px solid rgb(211 211 211); margin-left: 20px; width: 96%"
      @selection-change="handleSelectionChange"
    >
      <!-- 下拉表格 -->
      <!--<el-table-column type="expand">-->
      <!--  <template>-->
      <!--    <el-row :gutter="20">-->
      <!--      &lt;!&ndash; 左边内容 &ndash;&gt;-->
      <!--      <el-col :span="8">-->
      <!--        <el-form-->
      <!--          ref="productEditForm"-->
      <!--          label-position="left"-->
      <!--          inline-->
      <!--          class="demo-table-expand"-->
      <!--          :model="productEditForm"-->
      <!--        >-->
      <!--          <el-form-item :label="$t('product_item_product_44')">-->
      <!--            <el-input-->
      <!--              v-model="productEditForm.productSn"-->
      <!--              style="padding-left: 4px"-->
      <!--              disabled-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item :label="$t('product_item_product_45')">-->
      <!--            <el-input-->
      <!--              v-model="productEditForm.productName"-->
      <!--              style="padding-left: 24px"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item-->
      <!--            v-hasRole="['admin', 'purchaser']"-->
      <!--            mode="hide"-->
      <!--            :label="$t('product_item_product_62')"-->
      <!--            prop="imageUrl"-->
      <!--          >-->
      <!--            <el-upload-->
      <!--              ref="upload3"-->
      <!--              class="upload-demo"-->
      <!--              action="http://localhost:8101/file/upload"-->
      <!--              :on-change="handleFileChange"-->
      <!--              :on-remove="handleRemoveImage"-->
      <!--              :limit="1"-->
      <!--              :auto-upload="false"-->
      <!--            >-->
      <!--              <el-button-->
      <!--                slot="trigger"-->
      <!--                size="small"-->
      <!--                type="primary"-->
      <!--              >-->
      <!--                选取文件-->
      <!--              </el-button>-->
      <!--              <el-button-->
      <!--                style="margin-left: 10px"-->
      <!--                size="small"-->
      <!--                type="success"-->
      <!--                @click="upload('edit')"-->
      <!--              >-->
      <!--                上传到服务器-->
      <!--              </el-button>-->
      <!--              <div-->
      <!--                slot="tip"-->
      <!--                class="el-upload__tip"-->
      <!--              >-->
      <!--                只能上传一个jpg文件，且不超过2MB-->
      <!--              </div>-->
      <!--              <i-->
      <!--                v-if="uploadSuccess"-->
      <!--                class="el-icon-success"-->
      <!--              />-->
      <!--            </el-upload>-->
      <!--          </el-form-item>-->
      <!--          <el-form-item :label="$t('product_item_product_47')">-->
      <!--            <div class="block">-->
      <!--              <el-cascader-->
      <!--                v-model="productEditForm.categorySet"-->
      <!--                :options="categoryTree"-->
      <!--                :props="{-->
      <!--                  expandTrigger: 'hover',-->
      <!--                  multiple: true,-->
      <!--                  checkStrictly: true,-->
      <!--                }"-->
      <!--                clearable-->
      <!--              />-->
      <!--            </div>-->
      <!--          </el-form-item>-->
      <!--          <el-form-item :label="$t('product_item_product_63')">-->
      <!--            <el-input-->
      <!--              v-model="productEditForm.costPrice"-->
      <!--              style="padding-left: 12px"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item :label="$t('product_item_product_46')">-->
      <!--            <el-input-->
      <!--              v-model="productEditForm.salePrice"-->
      <!--              style="padding-left: 12px"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item :label="$t('product_item_product_50')">-->
      <!--            &lt;!&ndash; <span>{{ props.row.createTime }}</span> &ndash;&gt;-->
      <!--            <el-input-->
      <!--              v-model="productEditForm.createTime"-->
      <!--              disabled-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item size="small">-->
      <!--            <el-button-->
      <!--              v-hasRole="['admin', 'purchaser']"-->
      <!--              type="primary"-->
      <!--              class="query"-->
      <!--              style="width: 100px; margin-left: 10px; margin-right: 10px"-->
      <!--              @click="saveUpdate()"-->
      <!--            >-->
      <!--              保存-->
      <!--            </el-button>-->
      <!--            <el-button-->
      <!--              v-hasRole="['admin', 'purchaser']"-->
      <!--              type="primary"-->
      <!--              style="width: 100px"-->
      <!--              @click="reset"-->
      <!--            >-->
      <!--              重置-->
      <!--            </el-button>-->
      <!--          </el-form-item>-->
      <!--        </el-form>-->
      <!--      </el-col>-->
      <!--      &lt;!&ndash; 右边规格表 &ndash;&gt;-->
      <!--      <el-col :span="16">-->
      <!--        <el-row>-->
      <!--          <span class="specification">{{$t('product_item_product_64')}}</span>-->
      <!--          <el-button-->
      <!--            v-hasRole="['admin', 'purchaser']"-->
      <!--            mode="hide"-->
      <!--            type="primary"-->
      <!--            plain-->
      <!--            size="small"-->
      <!--            style="margin-bottom: 10px"-->
      <!--            @click="handleAddSpec"-->
      <!--          >-->
      <!--            新增规格-->
      <!--          </el-button>-->
      <!--        </el-row>-->
      <!--        <el-table-->
      <!--          border-->
      <!--          :data="specList"-->
      <!--          style="-->
      <!--            border: 1px solid rgb(211 211 211);-->
      <!--            margin-left: 20px;-->
      <!--            width: 96%;-->
      <!--          "-->
      <!--        >-->
      <!--          <el-table-column-->
      <!--            :label="$t('product_item_product_65')"-->
      <!--            align="center"-->
      <!--            prop="color"-->
      <!--          />-->
      <!--          <el-table-column-->
      <!--            :label="$t('product_item_product_66')"-->
      <!--            align="center"-->
      <!--            prop="size"-->
      <!--          />-->
      <!--          <el-table-column-->
      <!--            :label="$t('product_item_product_67')"-->
      <!--            align="center"-->
      <!--            prop="stock"-->
      <!--            width="220px"-->
      <!--          >-->
      <!--            <template v-slot="scope">-->
      <!--              <el-input-number-->
      <!--                v-model="scope.row.stock"-->
      <!--                mode="disabled"-->
      <!--                :min="1"-->
      <!--                :max="999"-->
      <!--                @change="handleStockChange(scope.row)"-->
      <!--              />-->
      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--          <el-table-column-->
      <!--            :label="$t('product_item_product_68')"-->
      <!--            align="center"-->
      <!--            class-name="small-padding fixed-width"-->
      <!--          >-->
      <!--            <template slot-scope="scope">-->
      <!--              <el-button-->
      <!--                v-hasRole="['admin', 'purchaser']"-->
      <!--                size="small"-->
      <!--                type="text"-->
      <!--                icon="el-icon-delete"-->
      <!--                @click="handleSepcDelete(scope.row)"-->
      <!--              >-->
      <!--                移除-->
      <!--              </el-button>-->
      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--        </el-table>-->
      <!--      </el-col>-->
      <!--    </el-row>-->
      <!--  </template>-->
      <!--</el-table-column>-->
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        :label="$t('product_item_product_44')"
        align="center"
        prop="productSn"
        width="100px"
      />
      <el-table-column
        show-overflow-tooltip
        :label="$t('product_item_product_69')"
        align="center"
        prop="productName"
        width="120"
      />
      <el-table-column :label="$t('product_item_product_62')" align="center" width="160px">
        <template slot-scope="scope">
          <img
            v-if="scope.row.imageUrl != null"
            :src="scope.row.imageUrl"
            alt="Product Image"
            style="width: 120px; height: auto"
          />
          <span v-else>{{$t('product_item_product_70')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        :label="$t('product_item_product_47')"
        align="center"
        prop="categorySet"
        width="85"
      />
      <el-table-column
        :label="$t('product_item_product_63')"
        align="center"
        prop="costPrice"
        width="100"
      />
      <el-table-column
        :label="$t('product_item_product_46')"
        align="center"
        prop="salePrice"
        width="100"
      />
      <el-table-column :label="$t('product_item_product_48')" align="center" width="80px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="success" effect="dark">{{$t('product_item_product_71')}}</el-tag>
          <el-tag v-if="scope.row.status == 1" type="warning" effect="dark">{{$t('product_item_product_72')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        :label="$t('product_item_product_50')"
        align="center"
        prop="createTime"
        width="110px"
      />
      <el-table-column :label="$t('product_item_product_68')" align="center">
        <template slot-scope="scope">
          <el-button
            
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSpecEdit(scope.row)"
          >{{$t('product_item_product_73')}}</el-button>
          <el-button
            v-hasRole="['admin', 'purchaser']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >{{$t('product_item_product_74')}}</el-button>
          <el-button
            v-show="scope.row.status == 0"
            v-hasRole="['admin', 'purchaser']"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="updateProdStatus(scope.row, 1)"
          >{{$t('product_item_product_72')}}</el-button>
          <el-button
            v-show="scope.row.status == 1"
            v-hasRole="['admin', 'purchaser']"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="updateProdStatus(scope.row, 0)"
          >{{$t('product_item_product_75')}}</el-button>
          <el-button
            v-hasRole="['admin', 'purchaser']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleProductDelete(scope.row)"
          >{{$t('product_item_product_76')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页加载 -->
    <el-pagination
      :current-page="showAllParams.current"
      :page-sizes="[5, 10, 20]"
      :page-size="showAllParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增产品弹窗，默认不显示 -->
    <el-dialog
      :title="$t('product_item_product_58')"
      :visible.sync="insertProductOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="productForm"
        :model="productForm"
        :rules="productFormrules"
        label-width="80px"
      >
        <el-form-item :label="$t('product_item_product_45')" prop="productName">
          <el-input
            v-model="productForm.productName"
            :placeholder="$t('product_item_product_77')"
          />
        </el-form-item>
        <el-form-item :label="$t('product_item_product_62')" prop="imageUrl">
          <el-upload
            ref="upload1"
            v-hasRole="['admin', 'purchaser']"
            class="upload-demo"
            action="http://localhost:8101/file/upload"
            :on-change="handleFileChange"
            :on-remove="handleRemoveImage"
            :limit="1"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">{{$t('product_item_product_78')}}</el-button>
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="upload"
            >{{$t('product_item_product_79')}}</el-button>
            <div slot="tip" class="el-upload__tip">{{$t('product_item_product_80')}}</div>
            <i v-if="uploadSuccess" class="el-icon-success" />
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('product_item_product_47')" prop="categories">
          <div class="block">
            <el-cascader
              v-model="productForm.categorySet"
              :options="categoryTree"
              :props="{
                expandTrigger: 'hover',
                multiple: true,
                checkStrictly: true,
              }"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item :label="$t('product_item_product_63')" prop="costPrice">
          <el-input
            v-model="productForm.costPrice"
            :placeholder="$t('product_item_product_81')"
          />
        </el-form-item>
        <el-form-item :label="$t('product_item_product_46')" prop="salePrice">
          <el-input
            v-model="productForm.salePrice"
            :placeholder="$t('product_item_product_82')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{$t('product_item_product_83')}}</el-button>
        <el-button
          v-hasRole="['admin', 'purchaser']"
          type="primary"
          @click="submitProductForm"
        >{{$t('product_item_product_84')}}</el-button>
      </div>
    </el-dialog>
    <!-- 修改产品 -->
    <el-dialog
      :title="$t('product_item_product_85')"
      :visible.sync="editProductOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="productEditForm"
        label-position="left"
        inline
        class="demo-table-expand"
        :model="productEditForm"
      >
        <el-form-item :label="$t('product_item_product_45')">
          <el-input
            v-model="productEditForm.productName"
            style="padding-left: 24px"
          />
        </el-form-item>
        <el-form-item
          v-hasRole="['admin', 'purchaser']"
          mode="hide"
          :label="$t('product_item_product_62')"
          prop="imageUrl"
        >
          <el-upload
            ref="upload3"
            class="upload-demo"
            action="http://localhost:8101/file/upload"
            :on-change="handleFileChange"
            :on-remove="handleRemoveImage"
            :limit="1"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">{{$t('product_item_product_78')}}</el-button>
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="upload('edit')"
            >{{$t('product_item_product_79')}}</el-button>
            <div slot="tip" class="el-upload__tip">{{$t('product_item_product_80')}}</div>
            <i v-if="uploadSuccess" class="el-icon-success" />
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('product_item_product_47')">
          <div class="block">
            <el-cascader
              v-model="productEditForm.categorySet"
              :options="categoryTree"
              :props="{
                expandTrigger: 'hover',
                multiple: true,
                checkStrictly: true,
              }"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item :label="$t('product_item_product_63')">
          <el-input
            v-model="productEditForm.costPrice"
            style="padding-left: 12px"
          />
        </el-form-item>
        <el-form-item :label="$t('product_item_product_46')">
          <el-input
            v-model="productEditForm.salePrice"
            style="padding-left: 12px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{$t('product_item_product_83')}}</el-button>
        <el-button
          v-hasRole="['admin', 'purchaser']"
          type="primary"
          @click="saveUpdate"
        >{{$t('product_item_product_84')}}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('product_item_product_86')"
      :visible.sync="editSpecOpen"
      width="800px"
      append-to-body
    >
      <div>
        <el-row>
          <span class="specification">{{$t('product_item_product_64')}}</span>
          <el-button
            v-hasRole="['admin', 'purchaser']"
            mode="hide"
            type="primary"
            plain
            size="small"
            style="margin-bottom: 10px"
            @click="handleAddSpec"
          >{{$t('product_item_product_87')}}</el-button>
        </el-row>
        <el-table
          border
          :data="specList"
          style="
            border: 1px solid rgb(211 211 211);
            margin-left: 20px;
            width: 96%;
          "
          max-height="500px"
        >
          <el-table-column :label="$t('product_item_product_65')" align="center" prop="color" />
          <el-table-column :label="$t('product_item_product_66')" align="center" prop="size" />
          <el-table-column
            :label="$t('product_item_product_67')"
            align="center"
            prop="stock"
            width="220px"
          >
            <template v-slot="scope">
              <el-input-number
                v-model="scope.row.stock"
                :disabled="(roleKeys.length === 0 || (roleKeys.length === 1 && roleKeys[0] === 'cashier'))"
                mode="disabled"
                :min="1"
                :max="999"
                @change="handleStockChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product_item_product_68')"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-hasRole="['admin', 'purchaser']"
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleSepcDelete(scope.row)"
              >{{$t('product_item_product_88')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{$t('product_item_product_83')}}</el-button>
        <el-button
          v-hasRole="['admin', 'purchaser']"
          type="primary"
          @click="editSpecOpen = false"
        >{{$t('product_item_product_84')}}</el-button>
      </div>
    </el-dialog>

    <!-- 新增规格弹窗，默认不显示 -->
    <el-dialog
      :title="$t('product_item_product_87')"
      :visible.sync="insertSpecOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="specForm"
        :model="specForm"
        :rules="specFormrules"
        label-width="80px"
      >
        <el-form-item :label="$t('product_item_product_65')" prop="coloe">
          <el-input v-model="specForm.color" :placeholder="$t('product_item_product_89')" />
        </el-form-item>
        <el-form-item :label="$t('product_item_product_66')" prop="size">
          <el-input v-model="specForm.size" :placeholder="$t('product_item_product_90')" />
        </el-form-item>
        <el-form-item :label="$t('product_item_product_67')" prop="stock">
          <el-input-number v-model="specForm.stock" :min="1" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{$t('product_item_product_83')}}</el-button>
        <el-button
          v-hasRole="['admin', 'purchaser']"
          type="primary"
          @click="submitSpecForm(scope)"
        >{{$t('product_item_product_84')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addProduct,
  delProduct,
  delProductList,
  getProduct,
  getProductList,
  getProductVO,
  updateProduct,
  updateProductStatus,
  uploadFile,
} from "@/api/product";
import {
  addSpec,
  delSpec,
  getlistByProductId,
  getSpeclist,
  updateSpec,
} from "@/api/specification";
import { queryCategoryTree } from "@/api/category";
import { mapGetters } from "vuex";
import { exportProduct, importProduct } from "@/api/excel";
import { getFormatTime } from "@/utils/timeFormatter";
export default {
  name: "Product",
  data() {
    return {
      loading: false,
      specLoading: false,
      // 产品表格数据
      dataList: [],
      // 规格表格数据
      specList: [],
      // 分页展示所有产品參數
      showAllParams: {},
      // 查询参数
      queryParams: {
        categoryList: [],
        current: 1,
        size: 5,
        status: "",
        productSn: "",
        productName: "",
        minSalePrice: "",
        maxSalePrice: "",
        startTime: " ",
        endTime: " ",
      },
      // 上线时间数组
      createTime: [],
      // 展开行数组
      expands: [],
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      productNames: [],
      specNames: [],
      // 非单个禁用
      single: true,
      value: [],
      // 类别下拉框选项数据
      categoryTree: [],
      // 状态下拉框选项数据
      StatusOptions: [
        {
          value: "0",
          label: this.$t('product_item_product_71'),
        },
        {
          value: "1",
          label: this.$t('product_item_product_72'),
        },
      ],
      // 要删除的id
      delData: {
        id: "",
      },
      // 是否勾选多个
      isMultipleSelected: false,
      // 是否显示弹出层
      insertProductOpen: false,
      editProductOpen: false,
      editSpecOpen: false,
      insertSpecOpen: false,
      // 新增产品表单
      productForm: {
        categorySet: [],
      },
      // 修改产品表单
      productEditForm: {},
      // 新增规格表单
      specForm: {
        productId: "",
        color: "",
        size: "",
        stock: 1,
      },
      // 存放已选择的图片URL
      imageUrl: "",
      //图片上传相关
      uploadFileRequest: {
        biz: "product",
      },
      // 用来保存选中的文件
      selectedFile: null,
      //文件是否上传成功
      uploadSuccess: false,
      //导入文件
      excelList: [],
      // 表单校验
      productFormrules: {
        name: [{ required: true, message: this.$t('product_item_product_91'), trigger: "blur" }],
        costPrice: [
          { required: true, message: this.$t('product_item_product_92'), trigger: "blur" },
        ],
        salePrice: [
          { required: true, message: this.$t('product_item_product_93'), trigger: "blur" },
        ],
      },
      specFormrules: {
        color: [{ required: true, message: this.$t('product_item_product_94'), trigger: "blur" }],
        size: [{ required: true, message: this.$t('product_item_product_95'), trigger: "blur" }],
        stock: [{ required: true, message: this.$t('product_item_product_96'), trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapGetters(["roleKeys"]),
  },
  created() {
    this.getAllProduct();
    queryCategoryTree().then((res) => {
      this.categoryTree = res.data;
      // 进一步处理value为label
      this.categoryTree.forEach((first) => {
        first.value = first.label;
        first.children.forEach((second) => {
          second.value = second.label;
        });
      });
    });
  },
  methods: {
    // 更新产品信息
    saveUpdate() {
      const editParams = {
        ...this.productEditForm,
        categorySet: this._.flatten(this.productEditForm.categorySet),
      };
      updateProduct(editParams)
        .then(() => {
          this.$message.success(this.$t('product_item_product_97'));
          this.getAllProduct();
          this.cancel();
        })
        .catch(() => {
          this.$message.error(this.$t('product_item_product_98'));
        });
    },
    // 重置产品信息
    reset() {
      this.productEditForm = {};
      if (this.$refs.upload1&&this.$refs.upload1.fileList) {
        this.$refs.upload1.fileList = [];
      }
      if (this.$refs.upload2&&this.$refs.upload2.fileList) {
        this.$refs.upload3.fileList = [];
      }
      if (this.$refs.upload3&&this.$refs.upload3.fileList) {
        this.$refs.upload3.fileList = [];
      }
    },
    // 更新产品状态
    updateProdStatus(row, status) {
      const { id } = row;
      updateProductStatus({
        id,
        ids: null,
        isBatch: 0,
        status,
      });
      row.status = status;
    },
    // 更新库存方法
    handleStockChange(row) {
      const editStockParams = {
        id: row.id,
        stock: row.stock,
      };
      updateSpec(editStockParams)
        .then(() => {
          this.$message.success(this.$t('product_item_product_99'));
        })
        .catch(() => {
          this.$message.error(this.$t('product_item_product_100'));
        });
    },
    // 修改时间格式
    formatTime(date) {
      return getFormatTime(date);
    },
    // 展示所有产品数据
    getAllProduct() {
      this.loading = true;
      getProductList(this.showAllParams).then((response) => {
        this.dataList = response.data.records;
        this.dataList.forEach((item) => {
          item.createTime = this.formatTime(item.createTime);
        });
        this.total = Number(response.data.total);
        this.loading = false;
      });
    },
    // 编辑按钮操作
    handleEdit(row) {
      this.productEditForm = { ...row };
      this.editProductOpen = true;
    },
    // 规格管理操作
    handleSpecEdit(row) {
      this.editSpecOpen = true;
      this.specList = [...row.specList];
      this.specForm.productId = row.id;
    },
    // 点击表格事件/展开行事件
    async expandRow(currentRow, expandedRows) {
      if (expandedRows.length === 0) {
        return;
      }
      // 忽略关闭事件
      let expandedRowIds = expandedRows.map((row) => row.id);
      if (expandedRowIds.indexOf(currentRow.id) === -1) {
        // console.log("这是一个关闭操作", currentRow.id);
        return;
      }
      // 关闭其他行
      for (let row of expandedRows) {
        if (row.id == currentRow.id) {
          continue;
        }
        this.$refs.DataTable.toggleRowExpansion(row, false);
      }
      // 重置产品编辑表单
      this.productEditForm = { ...currentRow };
      // 重置规格列表
      this.specList = [...currentRow.specList];
      // console.log(this.productEditForm, this.specList);
      this.specForm.productId = currentRow.id;
    },
    // 展示查询的所有产品数据
    getQueryProductList(queryParams) {
      this.loading = true;
      getProductList(queryParams).then((response) => {
        this.dataList = response.data.records;
        this.total = Number(response.data.total);
        this.loading = false;
        this.imageUrl = response.data.imageUrl;
      });
    },
    // 搜索按钮操作
    handleQuery() {
      const queryParams = { ...this.queryParams };
      queryParams.startTime = this.createTime[0]?.slice(0, 10);
      queryParams.endTime = this.createTime[1]?.slice(0, 10);
      // flatten 类别数组
      queryParams.categoryList = this._.flatten(this.queryParams.categoryList);
      this.getQueryProductList(queryParams);
    },
    // 重置按钮操作
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.minSalePrice = null;
      this.queryParams.maxSalePrice = null;
      this.queryParams.categoryList = [];
      this.createTime = [];
      this.getAllProduct();
    },
    // 处理分页操作
    handleSizeChange(val) {
      this.showAllParams.pageSize = val;
      this.getAllProduct();
    },
    handleCurrentChange(val) {
      this.showAllParams.current = val;
      this.getAllProduct();
    },
    // 新增产品表单提交
    submitProductForm: function () {
      this.productForm.categorySet = this._.flatten(
        this.productForm.categorySet
      );
      this.$refs["productForm"].validate((valid) => {
        if (valid) {
          addProduct(this.productForm)
            .then((response) => {
              if (response.message === "ok") {
                this.$message.success(this.$t('product_item_product_101'));
                this.getAllProduct();
                this.cancel();
              }
            })
            .catch((error) => {
              // console.log(error);
              this.$message.error(this.$t('product_item_product_102'), error);
            });
        }
      });
    },
    // 删除/批量下架产品按钮操作
    batchOffProduct() {
      this.$confirm(this.$t('product_item_product_103'), this.$t('product_item_product_104'), {
        confirmButtonText: this.$t('product_item_product_105'),
        cancelButtonText: this.$t('product_item_product_106'),
        type: "warning",
      })
        .then(() => {
          const ids = [...this.ids];
          return updateProductStatus({
            ids,
            isBatch: 1,
            status: 1,
          });
        })
        .then((response) => {
          this.$message({
            type: "success",
            message: this.$t('product_item_product_107'),
          });
          this.getAllProduct();
        });
    },
    // 删除/批量删除产品按钮操作
    handleProductDelete(row) {
      const productName = row.productName || this.productNames;
      // console.log(productId);

      this.$confirm(
        this.$t('product_item_product_108') + productName + this.$t('product_item_product_109'),
        this.$t('product_item_product_104'),
        {
          confirmButtonText: this.$t('product_item_product_105'),
          cancelButtonText: this.$t('product_item_product_106'),
          type: "warning",
        }
      )
        .then(() => {
          // console.log(row.id);
          if (Array.isArray(this.ids) && this.ids.length > 1) {
            return delProductList(this.ids);
          } else {
            this.delData.id = row.id || this.ids[0];
            return delProduct(this.delData);
          }
        })
        .then((response) => {
          // console.log(response);
          this.$message({
            type: "success",
            message: this.$t('product_item_product_110'),
          });
          this.getAllProduct();
        })
        .catch(() => {
          // 用户取消了删除操作
          this.$message({
            type: "info",
            message: this.$t('product_item_product_111'),
          });
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log(selection)
      this.ids = selection.map((item) => item.id);
      this.productNames = selection.map((item) => item.productName);
      this.isMultipleSelected = (selection.length !== 0);
      // console.log(this.ids);
    },
    // 新增规格表单提交
    submitSpecForm: function () {
      this.$refs["specForm"].validate((valid) => {
        if (valid) {
          // console.log(this.specForm);
          addSpec(this.specForm)
            .then((response) => {
              // console.log(response);
              if (response.message === "ok") {
                this.$message.success(this.$t('product_item_product_112'));
                getlistByProductId(this.specForm.productId).then((res) => {
                  this.specList = res.data;
                });
                this.getAllProduct();
                this.insertSpecOpen = false;
              }
            })
            .catch((error) => {
              // console.log(error);
              this.$message.error(this.$t('product_item_product_113'), error);
            });
        }
      });
      this.$refs.upload1.fileList = [];
    },
    // 删除规格按钮操作
    handleSepcDelete(row) {
      const specId = row.id;
      const specName = row.color;
      this.$confirm(this.$t('product_item_product_108') + specName + this.$t('product_item_product_109'), this.$t('product_item_product_104'), {
        confirmButtonText: this.$t('product_item_product_105'),
        cancelButtonText: this.$t('product_item_product_106'),
        type: "warning",
      })
        .then(function () {
          return delSpec(specId);
        })
        .then(() => {
          this.specList = this.specList.filter((spec) => spec.id !== row.id);
          this.$message.success(this.$t('product_item_product_110'));
          getlistByProductId(this.specForm.productId).then((res) => {
            this.specList = res.data;
          });
          this.getAllProduct();
        })
        .catch((error) => {
          // console.log(error);
          this.$message.error(this.$t('product_item_product_114'), error);
        });
    },
    // 照片上传
    handleSuccess(response, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    //检查文件格式
    beforeUpload(file) {
      // 允许的文件类型
      const allowedTypes = [
        "image/jpeg",
        "image/jpg",
        "image/svg+xml",
        "image/png",
        "image/webp",
      ];
      // 文件大小限制为 1MB
      const isLt1M = file.size / 1024 / 1024 < 1;
      // 检查文件类型
      const isAllowedType = allowedTypes.includes(file.raw.type);
      // 如果文件类型不正确
      if (!isAllowedType) {
        this.$message.error(
          this.$t('product_item_product_115')
        );
      }
      // 如果文件大小超过 1MB
      else if (!isLt1M) {
        this.$message.error(this.$t('product_item_product_116'));
      }
      return isAllowedType && isLt1M; // 返回是否通过验证
    },
    //接收文件列表
    handleFileChange(file, fileList) {
      if (!this.beforeUpload(file)) {
        fileList.splice(0, 1);
      }
      // fileList 是一个文件列表，但因为限制了只能上传一个文件，所以只取第一个
      else this.selectedFile = fileList[0];
    },
    // 移除文件时检查文件列表
    handleRemoveImage(file, fileList) {
      if (fileList.length == 0) {
        this.uploadSuccess = false;
      }
    },
    // 上传
    async upload(bizType) {
      try {
        const response = await uploadFile(
          this.selectedFile.raw,
          this.uploadFileRequest
        );
        // console.log("upload", response.data);
        if (bizType === "edit") {
          this.productEditForm.imageUrl = response.data;
        } else {
          this.productForm.imageUrl = response.data;
        }
        // console.log("文件上传成功", response.data);
        this.$message({
          message: this.$t('product_item_product_117'),
          type: "success",
        });
        this.uploadSuccess = true;
      } catch (error) {
        console.error(this.$t('product_item_product_118'), error);
        this.$message.error(this.$t('product_item_product_119'));
      }
    },
    // 新增产品按钮操作
    handleAddProduct() {
      this.resetProductForm();
      this.insertProductOpen = true;
    },
    // 新增规格按钮操作
    handleAddSpec() {
      this.resetSpecForm();
      this.insertSpecOpen = true;
    },
    // 取消弹窗按钮
    cancel() {
      this.reset();
      this.specList = [];
      this.editSpecOpen = false;
      this.insertProductOpen = false;
      this.insertSpecOpen = false;
      this.editProductOpen = false;
      // this.resetForm()
      this.uploadSuccess = false;
      if (this.$refs.upload1 && this.$refs.upload1.fileList) {
        this.$refs.upload1.fileList = [];
      }
      if (this.$refs.upload2 && this.$refs.upload2.fileList) {
        this.$refs.upload3.fileList = [];
      }
      if (this.$refs.upload3 && this.$refs.upload3.fileList) {
        this.$refs.upload3.fileList = [];
      }
    },
    // 重置产品添加表单
    resetProductForm() {
      this.productForm = {};
    },
    // 重置规格添加表单
    resetSpecForm() {
      this.specForm.color = "";
      this.specForm.size = "";
      this.specForm.stock = 1;
    },
    // 导出文件
    async handleExportAll() {
      await exportProduct()
        .then((res) => {
          // console.log(res);
          const a = document.createElement("a"); // 创建一个新的 a 标签
          const url = window.URL.createObjectURL(res); // 创建一个 URL 对象，表示 Blob 对象的内容
          a.href = url; // 将 a 标签的 href 设置为 URL 对象
          a.download = this.$t('product_item_product_120'); // 设置文件名
          document.body.appendChild(a); // 触发点击事件
          a.click();
          // 清理
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        })
        .catch((e) => {
          this.$message.error(this.$t('product_item_product_121'));
        });
    },
    /*上传Excel文件*/
    async httpRequest(options, fileList) {
      //需要将文件转换为FormData格式
      const formData = new FormData();
      // 若为多个文件，只取第一个
      let file = Array.isArray(options.file) ? options.file[0] : options.file;
      // 将文件添加到 FormData 实例中
      formData.append("file", file.raw || file);
      await importProduct(formData)
        .then((res) => {
          this.$message.success(res.data);
          this.getAllProduct();
        })
        .catch((e) => {
          this.$message.error(this.$t('product_item_product_122'));
        });
    },
    handleBeforeUpload(rawFile) {
      const AllowExcelTypes = [
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.ms-excel",
      ];
      // console.log(rawFile.type);
      if (!AllowExcelTypes.includes(rawFile.type)) {
        this.$message.error(this.$t('product_item_product_123'));
        return false;
      }
      if (rawFile.size / 1024 / 1024 > 5) {
        this.$message.error(this.$t('product_item_product_124'));
        return false;
      }
      return true;
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        this.$t('product_item_product_125', [files.length])
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.form {
  border: 2px dashed rgb(211, 211, 211);
  padding: 20px;
  padding-bottom: 0px;
  margin: 10px 20px 20px 20px;
}

.warning {
  width: 130px;
  margin-left: 20px;
  margin-bottom: 10px;
}

.deletes {
  width: 130px;
  margin-left: 10px;
  margin-bottom: 10px;
}

.query {
  margin-left: 30px;
  width: 60px;
}

.avatar-uploader-icon .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-right: 10px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: inline;
}

.insertButton,
.insertButton:hover {
  width: 130px;
  background-color: #4ac1cd;
  color: white;
}

.insertButton:hover {
  background-color: #90ccd2;
}

.page {
  margin-top: 10px;
  margin-left: 280px;
}

/* 数据展示表格 */
.demo-table-expand {
  margin-left: 10px;
  font-size: 0;
}

.demo-table-expand label {
  width: 100px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 5px;
  width: 100%;
}

.specification {
  font-weight: bold;
  margin-left: 20px;
  margin-right: 10px;
}
</style>
<style>
.el-tooltip__popper {
  max-width: 20%;
}

.el-icon-success {
  margin-left: 20px;
  font-size: 20px;
  color: green;
}
.button-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}
.upload-demo {
  margin-left: 10px;
}
.upload-demo .el-button {
  height: 39px;
  font-size: 14px;
  background-color: #67c23a;
  border-color: #67c23a;
}
</style>
